package org.swimv2.servlet;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.swimv2.controller.GestioneAbilita;
import org.swimv2.controller.GestioneAbilitaRemote;
import org.swimv2.controller.GestioneLogin;
import org.swimv2.controller.GestioneLoginRemote;
import org.swimv2.controller.GestioneRegistrazione;
import org.swimv2.controller.GestioneRegistrazioneRemote;
import org.swimv2.exception.InvalidLoginException;
import org.swimv2.exception.RegistrazioneNonValidaException;
import org.swimv2.model.Persona;
import org.swimv2.util.FormRegistrazione;





public class RegistrazioneServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	/**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrazioneServlet() {
        super();
    }

    
    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        Properties props = new Properties();
		props.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		Context ctx;
		try{
			
			ctx = new InitialContext(props);
			Object obj = ctx.lookup(GestioneAbilita.JNDI_NAME);
			GestioneAbilitaRemote managerAbilita = (GestioneAbilitaRemote)PortableRemoteObject.narrow(obj,GestioneAbilitaRemote.class);
			Collection<String> listAb=managerAbilita.getListaAbilita();
			request.setAttribute("listAb", listAb);
			request.getRequestDispatcher("WEB-INF/registrati.jsp").
			forward(request, response);	
		
		}catch(NamingException e){
			e.printStackTrace();}	
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        Properties props = new Properties();
		props.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		Context ctx;
		try{
			
			ctx = new InitialContext(props);
			Object obj = ctx.lookup(GestioneRegistrazione.JNDI_NAME);
			GestioneRegistrazioneRemote manager = (GestioneRegistrazioneRemote)PortableRemoteObject.narrow(obj,GestioneRegistrazioneRemote.class);
			
			String nome = null;
			String cognome = null;
			String username = null;
			String email = null;
			String password = null;
			
			String regione = null;
			String sede = null;
			
			String ab[];
			String abSupp[];
			ArrayList<String> abL = new ArrayList<String>();
			ArrayList<String> abSuppL = new ArrayList<String>();
			
			byte[] foto = null;
			try {
		        @SuppressWarnings("unchecked")
				List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	
		        for (FileItem item : items) {
		            if (item.isFormField()) {
		            	 if(item.getFieldName().equals("nome")){
		            		 nome = item.getString();
		            	 }
		            	 if(item.getFieldName().equals("cognome")){
		            		 cognome = item.getString();
		            	 }
		            	 if(item.getFieldName().equals("email")){
		            		 email = item.getString();
		            	 }
		            	 if(item.getFieldName().equals("username")){
		            		 username = item.getString();
		            	 }
		            	 if(item.getFieldName().equals("password1")){
		            		 password = item.getString();
		            	 }
		            	 if(item.getFieldName().equals("regione")){
		            		 regione = item.getString();
		            	 }
		            	 if(item.getFieldName().equals("ab")){
		            		 abL.add(item.getString());
		            	 }
		            	 if(item.getFieldName().equals("abSuppl")){
		            		 abSuppL.add(item.getString());
		            	 }
		                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
		            	
		                //String fieldvalue = item.getString();
		            	//String fieldname = item.getFieldName();
		            } else {
		                // Process form file field (input type="file").
		                //String fieldname = item.getFieldName();
		                //String filename = FilenameUtils.getName(item.getName());
		                java.io.InputStream filecontent = (java.io.InputStream) item.getInputStream();
		                foto = IOUtils.toByteArray(filecontent);

		            }
		        }
		        
		    } catch (FileUploadException e) {
		        throw new ServletException("Cannot parse multipart request.", e);

		    }
			
			ab=new String[abL.size()];
			abSupp=new String[abSuppL.size()];
			int i=0;
			for(String temp: abL)
			{
				ab[i]=temp;
				i++;
			}
			i=0;
			for(String temp: abSuppL)
			{
				abSupp[i]=temp;
				i++;
			}
	
			RequestDispatcher disp;
			FormRegistrazione form= new FormRegistrazione(nome,cognome,username,email,password,regione,sede,ab,abSupp,foto);
			
			try{
				
				manager.validaRegistrazione(form);
				
				// quando faccio la registrazione e va a buon fine ho un login implicito giusto?
				ctx = new InitialContext(props);
				obj = ctx.lookup(GestioneLogin.JNDI_NAME);
				GestioneLoginRemote managerLog = (GestioneLoginRemote)PortableRemoteObject.narrow(obj,GestioneLoginRemote.class);
				Persona u;
				try {
					u = managerLog.validaLogin(username, password);
					request.getSession().setAttribute("utente", u);
					disp = request.getRequestDispatcher("WEB-INF/benvenuto.jsp");
					disp.forward(request, response);
					// fine login
				} catch (InvalidLoginException e) {
					disp = request.getRequestDispatcher("/Registrazione");
					e.printStackTrace();
					disp.forward(request, response);
				}
				
				
			}
			catch(RegistrazioneNonValidaException e){
				request.setAttribute("messaggio", e.getErrore());
				Properties props2 = new Properties();
				props2.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
				props2.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
				props2.put(Context.PROVIDER_URL, "jnp://localhost:1099");
				Context ctx2;
				try{
					
					ctx2 = new InitialContext(props2);
					Object obj2 = ctx2.lookup(GestioneAbilita.JNDI_NAME);
					GestioneAbilitaRemote managerAbilita = (GestioneAbilitaRemote)PortableRemoteObject.narrow(obj2,GestioneAbilitaRemote.class);
					Collection<String> listAb=managerAbilita.getListaAbilita();
					request.setAttribute("listAb", listAb);
					request.setAttribute("messaggio", e.getErrore());
					
					request.setAttribute("nome",nome);
					request.setAttribute("cognome",cognome);
					request.setAttribute("username",username);
					request.setAttribute("email",email);
					request.setAttribute("regione",regione);
					
					request.getRequestDispatcher("WEB-INF/registrati.jsp").
					forward(request, response);	
				
				}catch(NamingException e1){
					e1.printStackTrace();}	
				//disp = request.getRequestDispatcher("/Registrazione");
				//disp.forward(request, response);
			}
			
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
	}

	private String readString(java.io.InputStream is) throws IOException {
		  char[] buf = new char[2048];
		  Reader r = new InputStreamReader(is, "UTF-8");
		  StringBuilder s = new StringBuilder();
		  int n; 
		  while((n = r.read(buf)) >= 0) 
		  { 
			  s.append(buf, 0, n); 
			  }
		  return s.toString();
		}
	
}
